<template>
    <div class="homeHeader">
        <div class="title" :style="isAdmin?'width:100%':'width:1700px'">
            <i @click="goHome">TIM</i>
            <el-dropdown class="userInfo" @command="fnCommand">
                      <span class="el-dropdown-link">
                        <span>{{user.name}}</span>
                          <div style="margin-left: 15px">
                              <el-badge class="mark"  :is-dot="messageNum>0">
                                <el-avatar size="large" :src="user.userFace"></el-avatar>
                              </el-badge>
                          </div>
                      </span>
                <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item>消息
                        <el-badge class="mark" :max="99" :value="messageNum"/>
                    </el-dropdown-item>
                    <el-dropdown-item :command="personalCenter.name">个人中心</el-dropdown-item>
                    <el-dropdown-item :command="personalSettings.name">设置</el-dropdown-item>
                    <el-dropdown-item :command="logout">注销登录</el-dropdown-item>
                </el-dropdown-menu>
            </el-dropdown>
        </div>
    </div>
</template>

<script>
    import {mapState} from "vuex";

    export default {
        name: "HomeHeader",
        data() {
            return {
                personalCenter: {},             //个人中心数据
                logout: 'logout',               //退出登录
                messageNum: 0,                  //消息数
                personalSettings:{},            //个人设置数据
            }
        },
        created() {
            this.init();
        },
        mounted() {
            // this.send();
        },
        computed: {
            routes() {
                return this.$store.state.routes
            },
            ...mapState({
                user: state => state.user,
                timeServiceApi: state => state.timeServiceApi,
                isAdmin: state => state.isAdmin,
            })
        },
        watch: { 
            routes: {
                immediate: true,
                deep: true,
                handler: function (newVal, oldVal) {
                    this.getPersonalCenter(newVal)
                }
            }
        },
        methods: {
            //获取id = 31，个人中心的路由
            getPersonalCenter(routers) {
                if (routers) {
                    routers.forEach(item => {
                        if (item.id == 33) {
                            this.personalCenter = item;
                        }else if (item.id == 31){
                            this.personalSettings = item;
                        } else if (item.children) {
                            this.getPersonalCenter(item.children);
                        }
                    })
                }
            },
            //退出登录
            fnCommand(command) {
                if (command == 'logout') {
                    this.$confirm("你确定要退出吗？( ╯□╰ )，是否继续？", "退出提示", {
                        confirmButtonText: "确定",
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        //退出登录先从后台去除该用户websocket的连接和rabbitMQ的监听
                        this.getRequest(this.timeServiceApi + "/logout/?userName=" + this.user.username).then(res => {
                            window.sessionStorage.removeItem('tokenStr')
                            window.sessionStorage.removeItem('user')
                            this.$store.commit('initRoutes', [])
                            this.$router.replace('/')
                            window.localStorage.setItem("openLogin", true);
                        })
                    }).catch(() => {
                        this.$message.info('已取消操作！')
                    })
                }
                if (command == this.personalCenter.name) {
                    this.$router.replace(this.personalCenter.path)
                }
                if (command == this.personalSettings.name){
                    this.$router.replace(this.personalSettings.path)
                }
            },
            //调回主页面
            goHome() {
                this.$router.replace('/home')
            },
            //初始化连接websocket
            init() {
                let that = this
                console.log("正在连接 ......");

                if (!window.WebSocket) {
                    window.WebSocket = window.MozWebSocket;
                }
                if (window.WebSocket) {
                    this.socket = new WebSocket("ws://127.0.0.1:1234/ws");
                    //消息返回事件
                    this.socket.onmessage = function (event) {
                        console.log("onmessage", event)
                        that.socketOnmessage(event.data)
                    }
                    //开启连接
                    this.socket.onopen = function (event) {
                        console.log("onopen", event)
                        sessionStorage.setItem("socket", JSON.stringify(that.socket));
                        that.send();
                    };
                    //关闭连接
                    this.socket.onclose = function (event) {
                        console.log("onclose", event)
                    };
                } else {
                    console.log("您的浏览器不支持WebSocket协议！");
                }
            },
            //用户连接
            send() {
                let message = '{"userId":"' + this.user.username + '"}'
                if (this.socket.readyState == WebSocket.OPEN) {
                    this.socket.send(message);
                    console.log("连接成功！")
                } else {
                    alert("WebSocket 连接没有建立成功！");
                }
            },
            //获取到socket的消息处理
            socketOnmessage(data) {
                let res = JSON.parse(data);
                if (res.data.noticeCount) {
                    this.messageNum += parseInt(res.data.noticeCount);
                }
                if (res.data.notice){
                    let notice = JSON.parse(res.data.notice);
                    this.messageNum += notice.cancelOrConfirm
                }
                if (this.messageNum < 0) this.messageNum = 0
                console.log("this.messageNum => ", this.messageNum)
            },
        }
    }
</script>

<style scoped>

    .homeHeader {
        background-color: #2a2d30;
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 0 15px;
        box-sizing: border-box;
        height: 60px;
        width: 100%;
        left: 0px;
    }

    .homeHeader .title {
        margin: auto;
        text-align: center;
    }

    .homeHeader .title i {
        font-size: 30px;
        font-family: 华文楷体;
        color: #FFFFFF;
    }

    .homeHeader .userInfo {
        cursor: pointer;
        float: right;
        margin-top: 10px;
    }

    .el-aside {
        background: #ffffff1f;
        position: fixed;
        top: 60px;

    }

    .el-dropdown-link {
        display: flex;
        align-items: center;
    }

    .el-dropdown {
        color: #c5c5c5;
    }

</style>
